package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.MemberLoginDto;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IMemberLoginService;
import com.zzyl.nursing.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

@Service
@Slf4j
public class MemberLoginServiceImpl implements IMemberLoginService {
    @Value("${wx.appid}")
    public String appid;
    @Value("${wx.secret}")
    public String secret;
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private TokenService tokenService;
    //获取openid接口
    public final static String OPENID_URL="https://api.weixin.qq.com/sns/jscode2session";
    public final static String PHONE_URL="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    public final static String ACCESS_TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token";
    @Override
    public LoginVo login(MemberLoginDto dto) {
        //1.先去微信那边获取Openid
        String openid = getOpenid(dto.getCode());
        if (!StringUtils.hasText(openid)){
            throw new BaseException("系统繁忙，请稍后再试");
        }
        //2.判断这个openid在表里面是否存在，family_member
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId,openid);
        FamilyMember familyMember = familyMemberMapper.selectOne(queryWrapper);
        //3.如果不存在，表示是新用户，我们需要新增一条数据
        if (familyMember==null){
            //3.1去获取手机号，插入数据
            String phone=getPhone(dto.getPhoneCode());
            familyMember= new FamilyMember();
            familyMember.setName("朴洪仁");
            familyMember.setPhone(phone);
            familyMember.setOpenId(openid);
            familyMember.setCreateTime(new Date());
            familyMemberMapper.insert(familyMember);
        }
        //4.生成jwt  Token,构造返回对象
        HashMap<String, Object> tokenBody = new HashMap<>();
        tokenBody.put("id",familyMember.getId());
        tokenBody.put("openid",openid);
        String token = tokenService.createToken(tokenBody);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());
        return loginVo;
    }

    /**
     * 获取access_token
     */
    private String getAccessToken(){
        log.info("获取accessToken");
        HashMap<String, Object> param = new HashMap<>();
        param.put("grant_type","client_credential");
        param.put("appid",appid);
        param.put("secret",secret);
        String response = HttpUtil.get(ACCESS_TOKEN_URL, param);
        log.info("获取accessToken返回:{}",response);
        return JSONUtil.parseObj(response).getStr("access_token");
    }
    /**
     * 获取手机号
     */
    private String getPhone(String phoneCode) {
        log.info("获取手机号开始");
        HashMap<String, Object> param = new HashMap<>();
        String accessToken = getAccessToken();
        param.put("code",phoneCode);
        String response = HttpUtil.post(PHONE_URL+accessToken, JSONUtil.toJsonStr(param));
        log.info("获取返回手机号：{}",response);
        JSON parse = JSONUtil.parse(response);
        return JSONUtil.getByPath(parse,"phone_info.phoneNumber")+"";


    }

    /**
     * 获取openid
     */
    public String getOpenid(String code){
        log.info("去获取openid");
        HashMap<String, Object> param = new HashMap<>();
        param.put("appid",appid);
        param.put("secret",secret);
        param.put("js_code",code);
        param.put("grant_type","authorization_code");
        String response = HttpUtil.get(OPENID_URL, param);
        log.info("获取Openid返回：{}",response);
        JSONObject jsonObject = JSONUtil.parseObj(response);
        return jsonObject.getStr("openid");
    }
}
